package models

import (
	"activity_srv/basic/config"
	"gorm.io/gorm"
	"time"
)

type CutUserHelp struct {
	Id       uint32         `gorm:"column:id;type:int UNSIGNED;comment:砍价用户帮助表ID;primaryKey;not null;" json:"id"` // 砍价用户帮助表ID
	Uid      uint32         `gorm:"column:uid;type:int UNSIGNED;comment:自己的用户id;not null;" json:"uid"`            // 自己的用户id
	ToHelpId int32          `gorm:"column:to_help_id;type:int;comment:帮助的用户id;not null;" json:"to_help_id"`       // 帮助的用户id
	JoinId   uint32         `gorm:"column:join_id;type:int UNSIGNED;comment:参加记录id;not null;" json:"join_id"`     // 参加记录id
	Price    float64        `gorm:"column:price;type:decimal(10, 2);comment:帮助砍价多少金额;not null;" json:"price"`     // 帮助砍价多少金额
	CreateAt time.Time      `gorm:"column:create_at;type:datetime;not null;" json:"create_at"`
	UpdateAt time.Time      `gorm:"column:update_at;type:datetime;not null;default:CURRENT_TIMESTAMP;" json:"update_at"`
	DeleteAt gorm.DeletedAt `gorm:"column:delete_at;type:datetime;default:NULL;" json:"delete_at"`
}

func (c *CutUserHelp) TableName() string {
	return "cut_user_help"
}

// 获取用户被帮过的数量
func (c *CutUserHelp) GetHelpRecordCount() int64 {
	var h CutUserHelp
	var count int64
	config.DB.Where("join_id = ?", c.JoinId).Find(&h).Count(&count)
	return count
}

func (c *CutUserHelp) CreateHelp(tx *gorm.DB) error {
	return tx.Create(&c).Error
}

// 获取帮过某用户的记录数量
func (c *CutUserHelp) GetHelpOneRecord() int64 {
	var h CutUserHelp
	var count int64
	config.DB.Where("join_id = ? and uid = ?",
		c.JoinId, c.Uid).Find(&h).Count(&count)
	return count
}

// 获取用户被帮助砍价记录的列表
func (c *CutUserHelp) ListByToUserId() (list []TwoTableHelpList, err error) {
	err = config.DB.Model(&CutUserHelp{}).Select("cut_user_help.id,cut_user_help.uid,"+
		"cut_user_help.join_id,cut_user_help.price,cut_user_help.to_help_id,user.nickname").Joins("join user on cut_user_help.to_help_id = user.id").
		Where("cut_user_help.to_help_id = ?", c.ToHelpId).Find(&list).Error
	return
}

// 获取用户主动帮助砍价记录列表
func (c *CutUserHelp) UserToHelpList() (list []TwoTableHelpList, err error) {
	err = config.DB.Model(&CutUserHelp{}).Select("cut_user_help.id,cut_user_help.uid,"+
		"cut_user_help.join_id,cut_user_help.price,cut_user_help.to_help_id,user.nickname").
		Joins("join user on cut_user_help.to_help_id = user.id").Where("uid = ?", c.Uid).Find(&list).Error
	return
}

// 帮助记录列表
func (c *CutUserHelp) HelpList() (list []TwoTableHelpList, err error) {
	err = config.DB.Model(&CutUserHelp{}).Select("cut_user_help.id,cut_user_help.uid," +
		"cut_user_help.join_id,cut_user_help.price,cut_user_help.to_help_id,user.nickname").
		Joins("join user on cut_user_help.to_help_id = user.id").
		Find(&list).Error
	return
}

type TwoTableHelpList struct {
	Id       uint32  `json:"id,omitempty"`
	Uid      uint32  `json:"uid,omitempty"`
	ToHelpId int32   `json:"to_help_id,omitempty"`
	JoinId   uint32  `json:"join_id,omitempty"`
	Price    float64 `json:"price,omitempty"`
	Nickname string  `json:"nickname,omitempty"`
}
